package cn.maydaymemory.mastery.configuration;

import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class LanguageManager{
    private Map<Locale, YamlConfiguration> languages;
    private File root;
    private JavaPlugin plugin;

    public LanguageManager(JavaPlugin plugin){
        this.plugin=plugin;
        languages=new HashMap<>();
        root=new File(plugin.getDataFolder(),"lang");
    }
    public void preload(){
        preload(Locale.getDefault());
    }
    public void preload(String languageTag){
       preload(Locale.forLanguageTag(languageTag));
    }
    public void preload(Locale locale){
        YamlConfiguration lang;
        File langPath = new File(root, "lang_" + locale.toString() + ".yml");
        lang=load(langPath);
        if(lang==null) lang = load(new File(root,"lang.yml"));
        if(lang!=null) languages.put(locale, lang);
    }

    private YamlConfiguration load(File langPath){
        YamlConfiguration lang = new YamlConfiguration();
        if(root.exists() || root.mkdirs()) {
            if (!langPath.exists()) {
                InputStream input = plugin.getResource(langPath.getName());
                if (input != null) {
                    try {
                        if (langPath.createNewFile()) {
                            OutputStream output = new FileOutputStream(langPath);
                            byte[] b = new byte[1024];
                            int length;
                            while ((length = input.read(b)) != -1) {
                                output.write(b, 0, length);
                            }
                            output.flush();
                            output.close();
                        }
                        input.close();
                        lang.load(langPath);
                    } catch (IOException | InvalidConfigurationException e) {
                        e.printStackTrace();
                    }
                } else lang = null;
            } else lang = YamlConfiguration.loadConfiguration(langPath);
        }else lang = null;
        return lang;
    }

    public YamlConfiguration getLang(){
        return getLang(Locale.getDefault());
    }
    public YamlConfiguration getLang(Locale locale){
        if (!languages.containsKey(locale)) preload(locale);
        return languages.get(locale);
    }
    public YamlConfiguration getLang(String languageTag){
        return getLang(Locale.forLanguageTag(languageTag));
    }
}
